package co.yixiang.retail.biz.user.sevice.imp;

import cn.hutool.core.date.DateUtil;
import co.yixiang.common.core.api.YshopException;
import co.yixiang.common.core.exception.UtilException;
import co.yixiang.common.mproot.common.service.impl.BaseServiceImpl;

import co.yixiang.common.mproot.common.utils.QueryHelpPlus;
import co.yixiang.common.mproot.dozer.service.IGenerator;
import co.yixiang.retail.biz.user.mapper.YxSystemStoreMapper;
import co.yixiang.retail.biz.user.sevice.ConsumerCodeService;
import co.yixiang.retail.biz.user.sevice.YxSystemStoreService;
import co.yixiang.retail.common.annotation.ServiceLock;
import co.yixiang.retail.common.domain.CreateCode;
import co.yixiang.retail.common.domain.YxSystemStore;
import co.yixiang.retail.common.domain.YxUser;
import co.yixiang.retail.common.dto.*;
import co.yixiang.upms.common.system.domain.User;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;


@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxSystemStoreServiceImpl extends BaseServiceImpl<YxSystemStoreMapper,YxSystemStore> implements YxSystemStoreService {
    private final  YxSystemStoreMapper yxSystemStoreMapper;
    private final IGenerator generator;

    private final ConsumerCodeService consumerCodeService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public List<YxSystemStore> selectList(String phone) {
        return yxSystemStoreMapper.selectListByPhone(phone);
    }

    @Override
    public Map<String, Object> queryByType(YxSystemStoreQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxSystemStore> page = new PageInfo<>(queryByType(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxSystemStoreDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public YxSystemStore queryBalace(Integer id) {
        List<YxSystemStore> yxSystemStores = yxSystemStoreMapper.queryBalace(id);
        if (CollectionUtils.isEmpty(yxSystemStores)){
            throw new YshopException("门店不存在");
        }
        if (yxSystemStores.size()>1){
            throw new YshopException("未知异常,请联系管理员");
        }
        return  yxSystemStores.get(0);
    }

    /**
     * 消費碼
     * @param map
     * @return
     */
    @Override
    public YxUser checkCode(Map<String, String> map) {
        String code = map.get("code");
        CreateCode createCode = mongoTemplate.findOne(new Query(Criteria.where("code").is(code)), CreateCode.class);
        if (ObjectUtils.isEmpty(createCode)) {
            throw new UtilException("用戶不存在");
        }
        return  yxSystemStoreMapper.getUserById(createCode.getUid());
    }
    /***
     * 1、更新销货码
     * 2、扣减购买者积分
     * 3、增加门店的 货款+服务费
     * 4、添加对应的日志
     * @param uid
     * @param storeId
     * @param money  支付金额
     * @param ryzUseIntegralDetailDto
     */
    @Override
    @ServiceLock
    public void updateSalesCode(Long uid,Integer storeId, BigDecimal money, RyzUseIntegralDetailDto ryzUseIntegralDetailDto) {
        YxBalanceChangeDto yxBalanceChangeDto = new YxBalanceChangeDto();
        /**查询购买者信息*/
        YxUser yxUser = yxSystemStoreMapper.getUserById(uid);
        BigDecimal beforeUsingIntegral = yxUser.getIntegral();
        /**查询门店店主信息、门店对应服务费*/
        YxUser user=yxSystemStoreMapper.getStoreUserById(storeId);
        BigDecimal charge = yxSystemStoreMapper.findServiceCharge(storeId);
        BigDecimal getCharge = money.multiply(charge).add(money);
        //门店的最终余额
        BigDecimal finalbalance = user.getStoreBalance().add(getCharge);
        if (beforeUsingIntegral.compareTo(money)<0){
           throw new UtilException("优惠卷不足");
       }
        String saleCode = ryzUseIntegralDetailDto.getSaleCode();
        CreateCode createCode = mongoTemplate.findOne(new Query(Criteria.where("code").is(saleCode)), CreateCode.class);
        if (ObjectUtils.isEmpty(createCode)) {
            throw new UtilException("用戶不存在");
        }if (!createCode.getUid().equals(uid)){
            throw new YshopException("请勿重复使用销货码");
        }
        /**消费后的积分余额*/
        BigDecimal afterUsingIntegral = beforeUsingIntegral.subtract(money);
       ryzUseIntegralDetailDto.setBeforeUsingIntegral(beforeUsingIntegral);
       ryzUseIntegralDetailDto.setAfterUsingIntegral(afterUsingIntegral);
       ryzUseIntegralDetailDto.setUsingIntegral(money);
        /**更新积分详情 ryz_use_integral_detail*/
        yxSystemStoreMapper.insertIntegralDetail(ryzUseIntegralDetailDto);
        yxSystemStoreMapper.updateIntegral(uid,afterUsingIntegral);
        /**更新门店店主的货款余额*/
        yxSystemStoreMapper.updateNowMoney(user.getUid(),finalbalance);
        yxBalanceChangeDto.setChangeTurn(user.getNowMoney());
        yxBalanceChangeDto.setChangePut(finalbalance);
        yxBalanceChangeDto.setUid(user.getUid().intValue());
        yxBalanceChangeDto.setUserFront(getCharge);
        yxBalanceChangeDto.setType(9);
        yxSystemStoreMapper.insertBlanceChange(yxBalanceChangeDto);
        //更新销货码
        String code = consumerCodeService.createCode(null, uid);
        if (null==code){
            throw new UtilException("未知异常,请联系管理员");
        }
    }
    @Override
    public UserDto findByPhone(String phone) {
        //根据手机号 查询登录用户
        User user = yxSystemStoreMapper.login(phone);
        if(user == null) {
            throw new YshopException("当前用户不存在");
        }
        //用户所属岗位
        user.setJob(null);
        //用户所属部门
        user.setDept(null);
        return generator.convert(user, UserDto.class);

    }
    @Override
    public YxUser findUserById(Long id) {
       return yxSystemStoreMapper.findYxUserById(id);
    }

    @Override
    public void updatePass(Long uid, String encryptPassword) {
        yxSystemStoreMapper.updatePass(encryptPassword,uid);
    }


    @Override
    public void updateMoney(BigDecimal payPrice, Long uid,BigDecimal oldPrice) {
        //追加门店余额变化明细
        BigDecimal subtract = oldPrice.subtract(payPrice);
        YxBalanceChangeDto yxBalanceChangeDto = new YxBalanceChangeDto();
        yxBalanceChangeDto.setChangeTurn(oldPrice);
        yxBalanceChangeDto.setChangePut(subtract);
        yxBalanceChangeDto.setUid(uid.intValue());
        yxBalanceChangeDto.setUserFront(payPrice);
        yxBalanceChangeDto.setType(9);
        yxSystemStoreMapper.updateMoney(subtract,uid);
        yxSystemStoreMapper.insertBlanceChange(yxBalanceChangeDto);
    }

    //TODO 待更新
    @Override
    public BigDecimal findServiceCharge(Integer storId) {
//        yxSystemStoreMapper.findServiceCharge()
        return null;
    }

    /***
     * 门店充值中心
     * @return
     */
    @Override
    public Boolean recharge(Integer retailId) {
        return yxSystemStoreMapper.selectRecharge(retailId);
    }

    @Override
    public void updateBanlance(Long uid, BigDecimal extractPrice) {
        yxSystemStoreMapper.updateBanlance(uid,extractPrice);
    }

    @Override
    public BigDecimal queryStoreBalance(Long uid) {
        BigDecimal bigDecimal = yxSystemStoreMapper.queryStoreBalance(uid);
        return bigDecimal;
    }


    public List<YxSystemStore> queryAll(YxSystemStoreQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxSystemStore.class, criteria));
    }

    public List<YxSystemStore>  queryByType(YxSystemStoreQueryCriteria criteria){
        Integer retailId = criteria.getRetailId();
        Integer retailType = criteria.getRetailType();
        if (null==retailId){
            return new ArrayList<>();
        }
        if (retailType==0){
            return new ArrayList<>();
        }
//        YxSystemStore yxSystemStore = baseMapper.selectById(retailId);
//            if (null!=yxSystemStore){
//                retailType = yxSystemStore.getRetailType();
//            if (retailType==0){
//            return new ArrayList<>();
//            }
//        }
        return yxSystemStoreMapper.queryByType(criteria);
    }
}
